/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.desmond.squarecamera;

import ohos.agp.components.*;
import ohos.app.Context;

public class SquareLayout extends ComponentContainer implements
        ComponentContainer.EstimateSizeListener,
        ComponentContainer.ArrangeListener {

    private int squareLen = 0;

    public SquareLayout(Context context) {
        this(context, null);
    }

    public SquareLayout(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public SquareLayout(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        setEstimateSizeListener(this);
        setArrangeListener(this);
    }


    @Override
    public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {

        int width = Component.EstimateSpec.getSize(widthEstimateConfig);
        int height = Component.EstimateSpec.getSize(heightEstimateConfig);

        squareLen = width > height ? height : width;

        setEstimatedSize(squareLen, squareLen);

        return true;
    }

    @Override
    public boolean onArrange(int left, int top, int width, int height) {
        Component childView = getComponentAt(0);
        if (childView != null) {
            childView.arrange(0, 0, squareLen, squareLen);
        }
        return true;
    }

}
